//
//  SceneryViewController.m
//  Travelmemory
//
//  Created by lanou3g on 16/3/31.
//  Copyright © 2016年 ABCD. All rights reserved.
//

#import "SceneryViewController.h"
#import "HeaderView.h"
#import "SceneryListViewController.h"
#import "TitleTableViewCell.h"
#import "TravelHelper.h"
#import "NearDetailModel.h"
#import "NearMapViewController.h"
#import "UMSocialDataService.h"

#import "UIImageView+WebCache.h"
#define kScreenW  self.view.frame.size.width

@interface SceneryViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, UMSocialDataDelegate>

@property (nonatomic,strong)HeaderView *headVC;

@property (nonatomic, strong) NSMutableArray *titleArray;

@property (nonatomic, strong) NSMutableArray *sectionArray;
@property (nonatomic, strong) UILabel *titlename; // 标题
@property (nonatomic, strong) NearDetailModel *model;

@end

@implementation SceneryViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    // navagationBar变透明
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigation_bar_background"] forBarMetrics:UIBarMetricsDefault];
    
    // navagationBar下面一像素的黑线变白色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    // 显示tabBar
    self.tabBarController.tabBar.hidden = YES;
 
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigation_bar_background"] forBarMetrics:UIBarMetricsDefault];
    
    // navagationBar下面一像素的黑线变白色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *mapButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"dest_map_route"] style:(UIBarButtonItemStyleDone) target:self action:@selector(mapButtonAction)];
    
    UIBarButtonItem *shareButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-share"] style:(UIBarButtonItemStyleDone) target:self action:@selector(shareButtonAction)];
    
    self.navigationItem.rightBarButtonItems = @[mapButton,shareButton];
    
    // 解析数据
    [self resolveData];
    
    self.headVC = [[HeaderView alloc] initWitTableViewWithHeaderImage:[UIImage imageNamed:@"11"] withheaderImageHight:200];
    if (self.cover_s.length != 0) {
        [self.headVC.headerImageView sd_setImageWithURL:[NSURL URLWithString:self.cover_s] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            self.headVC = [[HeaderView alloc] initWitTableViewWithHeaderImage:image withheaderImageHight:200];
        }];
    }
    
    // 设置代理
    self.headVC.tableView.delegate = self;
    self.headVC.tableView.dataSource = self;
    [self.view addSubview:self.headVC];
    
    self.titleArray = @[@"", @"概况", @"地址", @"到达方式", @"联系方式"].mutableCopy;



}

#pragma mark - 解析数据
- (void)resolveData {
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/5/%@/", self.ID];
    [[TravelHelper defaultTravelHelper] get:urlStr params:nil success:^(id responseObj) {
        NearDetailModel *model = [[NearDetailModel alloc] init];
        [model setValuesForKeysWithDictionary:responseObj];
        [model setValue:responseObj[@"id"] forKey:@"ID"];
        [model setValue:responseObj[@"location"][@"lat"] forKey:@"lat"];
        [model setValue:responseObj[@"location"][@"lng"] forKey:@"lng"];
        self.model = model;
        [self.headVC.tableView reloadData];
    } failure:^(NSError *error) {
        
        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络链接失败,请查看网络连接" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        
        [view show];
    }];
    
}

#pragma mark  tableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //return self.titleArray.count;
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    //self.titlename.text = self.model.name;
    switch (indexPath.section) {
        case 1: {
            cell.textLabel.text = self.model.Description;
            cell.textLabel.numberOfLines = 0;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            break;
        }
        case 2: {
            cell.textLabel.text = self.model.address;
            cell.textLabel.numberOfLines = 0;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        }
        case 3: {
            cell.textLabel.text = self.model.arrival_type;
            cell.textLabel.numberOfLines = 0;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            break;
        }
        case 4: {
            cell.textLabel.text = self.model.tel;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        }
        default:
            break;
    }
    return cell;
    
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    CGFloat offset = scrollView.contentOffset.y;
    if (offset < -50) {
        SceneryListViewController *secondVC = [[SceneryListViewController alloc] init];
        
        // 属性传值
        secondVC.scenerys = self.model.ID;
        secondVC.sceneryName = self.name;
        secondVC.sceneryType = self.model.type;
//        NSLog(@"%@", self.model.type);
        [self.navigationController pushViewController:secondVC animated:YES];
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section != 0) {
        return [self.titleArray objectAtIndex:section];
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //当手指离开某行时，就让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 2: {
            // 跳转地图
            NearMapViewController *nearMapVC = [[NearMapViewController alloc] init];
            nearMapVC.lat = self.model.lat;
            nearMapVC.lng = self.model.lng;
            nearMapVC.name = self.name;
            
            nearMapVC.address = self.model.address;
            [self showViewController:nearMapVC sender:nil];
            break;
        }
        case 4: {
            if (self.model.tel.length != 0) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认拨打电话" message:nil preferredStyle:UIAlertControllerStyleAlert];
                // 2.取消按钮
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [alert addAction:cancelAction];
                // 3.确定按钮
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    // 拨打电话
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", self.model.tel]]];
                    NSLog(@"拨打电话");
                }];
                [alert addAction:okAction];
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
            }
            break;
        }
        default:
            break;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 1: {
            if ([self p_hightWithString:self.model.Description] < 40) {
                return 40;
            }else {
                return [self p_hightWithString:self.model.Description] + 40;
            }
            break;
        }
        case 2: {
            return 40;
            break;
        }
        case 3: {
            if ([self p_hightWithString:self.model.arrival_type] < 40) {
                return 40;
            }else {
                return [self p_hightWithString:self.model.arrival_type] + 40;
            }
            break;
        }
        default:
            break;
    }
    return 40;
    
}

#pragma mark - 头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view  = [[UIView alloc]init];
        self.titlename = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, kScreenW, 30)];
        self.titlename.text = self.name;
        self.titlename.textAlignment = NSTextAlignmentCenter;
        self.titlename.font = [UIFont systemFontOfSize:20];
        [view addSubview:_titlename];
        //view.backgroundColor = [UIColor redColor];
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        
        return 60;
    }
    return 30;
}

// 输入一段文字.返回修改文字高度
// 私有的方法,用来输入一段文字,返回文字高度
-(CGFloat)p_hightWithString:(NSString *)aString {
    
    return [aString boundingRectWithSize:CGSizeMake(kScreenW, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;
}


// 地图
- (void)mapButtonAction{
    NearMapViewController *nearMapVC = [[NearMapViewController alloc] init];
    nearMapVC.lat = self.model.lat;
    nearMapVC.lng = self.model.lng;
    nearMapVC.name = self.name;
    nearMapVC.address = self.model.address;
    [self showViewController:nearMapVC sender:nil];
    
}
// 分享
- (void)shareButtonAction{
    NSString *shareUrl = [NSString stringWithFormat:@"http://web.breadtrip.com%@", self.model.url];
    NSString *shareText = [NSString stringWithFormat:@"开心的旅行由心开始... %@", shareUrl];
    
//    [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:self.cover_s];
//    [UMSocialSnsService presentSnsIconSheetView:self
//                                         appKey:@"5637119d67e58e75ae00184d"
//                                      shareText:shareText
//                                     shareImage:nil
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatFavorite,UMShareToWechatSession,UMShareToWhatsapp,UMShareToQQ,UMShareToQzone,UMShareToWechatTimeline,UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToSms,UMShareToEmail,nil]
//                                       delegate:self];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
